<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>流程监控 - 员工请假审批系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/daisyui/4.12.10/full.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.6.7/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
</head>
<body class="bg-base-200 min-h-screen">
<!-- 导航栏 -->
<div class="navbar bg-primary text-primary-content shadow-lg">
    <div class="navbar-start">
        <a href="/leave/" class="btn btn-ghost text-xl font-bold">
            <i class="fas fa-calendar-check mr-2"></i>
            请假审批系统
        </a>
    </div>
    <div class="navbar-center hidden lg:flex">
        <ul class="menu menu-horizontal px-1">
            <li><a href="/leave/" class="btn btn-ghost">首页</a></li>
            <li><a href="/leave/apply" class="btn btn-ghost">请假申请</a></li>
            <li><a href="/leave/manager" class="btn btn-ghost">领导审批</a></li>
            <li><a href="/leave/boss" class="btn btn-ghost">老板审批</a></li>
            <li><a href="/leave/monitor" class="btn btn-ghost btn-active">流程监控</a></li>
        </ul>
    </div>
</div>

<!-- 主要内容 -->
<div class="container mx-auto px-4 py-8">
    <!-- 页面标题 -->
    <div class="text-center mb-8">
        <h1 class="text-4xl font-bold text-base-content mb-4">
            <i class="fas fa-chart-line text-info mr-3"></i>
            流程监控中心
        </h1>
        <p class="text-lg text-base-content/70">实时监控请假审批流程状态和统计数据</p>
    </div>

    <!-- 实时统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="stat bg-gradient-to-br from-blue-500 to-blue-600 text-white shadow-xl rounded-2xl">
            <div class="stat-figure text-white/80">
                <i class="fas fa-play-circle text-3xl"></i>
            </div>
            <div class="stat-title text-white/90">运行中流程</div>
            <div class="stat-value text-white" id="runningProcesses">0</div>
            <div class="stat-desc text-white/80">正在处理中</div>
        </div>
        <div class="stat bg-gradient-to-br from-green-500 to-green-600 text-white shadow-xl rounded-2xl">
            <div class="stat-figure text-white/80">
                <i class="fas fa-check-circle text-3xl"></i>
            </div>
            <div class="stat-title text-white/90">已完成流程</div>
            <div class="stat-value text-white" id="completedProcesses">0</div>
            <div class="stat-desc text-white/80">本月完成</div>
        </div>
        <div class="stat bg-gradient-to-br from-yellow-500 to-yellow-600 text-white shadow-xl rounded-2xl">
            <div class="stat-figure text-white/80">
                <i class="fas fa-clock text-3xl"></i>
            </div>
            <div class="stat-title text-white/90">平均处理时间</div>
            <div class="stat-value text-white" id="avgProcessTime">0</div>
            <div class="stat-desc text-white/80">小时</div>
        </div>
        <div class="stat bg-gradient-to-br from-purple-500 to-purple-600 text-white shadow-xl rounded-2xl">
            <div class="stat-figure text-white/80">
                <i class="fas fa-percentage text-3xl"></i>
            </div>
            <div class="stat-title text-white/90">通过率</div>
            <div class="stat-value text-white" id="approvalRate">0%</div>
            <div class="stat-desc text-white/80">本月统计</div>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <!-- 流程状态分布图 -->
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body">
                <h2 class="card-title text-xl mb-4">
                    <i class="fas fa-pie-chart text-info mr-2"></i>
                    流程状态分布
                </h2>
                <div class="h-64">
                    <canvas id="statusChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 每日申请趋势图 -->
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body">
                <h2 class="card-title text-xl mb-4">
                    <i class="fas fa-line-chart text-success mr-2"></i>
                    每日申请趋势
                </h2>
                <div class="h-64">
                    <canvas id="trendChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 流程实例列表 -->
    <div class="card bg-base-100 shadow-xl mb-8">
        <div class="card-body">
            <div class="flex justify-between items-center mb-6">
                <h2 class="card-title text-2xl">
                    <i class="fas fa-list-alt text-primary mr-2"></i>
                    流程实例监控
                </h2>
                <div class="flex space-x-2">
                    <select class="select select-bordered select-sm" id="statusFilter" onchange="filterProcesses()">
                        <option value="all">全部状态</option>
                        <option value="running">运行中</option>
                        <option value="completed">已完成</option>
                    </select>
                    <button class="btn btn-primary btn-sm" onclick="loadProcesses()">
                        <i class="fas fa-sync-alt mr-1"></i>
                        刷新
                    </button>
                </div>
            </div>

            <!-- 流程列表 -->
            <div class="overflow-x-auto">
                <table class="table table-zebra w-full">
                    <thead>
                    <tr>
                        <th>流程ID</th>
                        <th>申请人</th>
                        <th>请假天数</th>
                        <th>当前状态</th>
                        <th>开始时间</th>
                        <th>处理时长</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="processTableBody">
                    <!-- 流程数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 空状态 -->
            <div id="emptyState" class="text-center py-12 hidden">
                <i class="fas fa-search text-6xl text-base-content/30 mb-4"></i>
                <h3 class="text-xl font-bold text-base-content/70 mb-2">暂无流程数据</h3>
                <p class="text-base-content/50">还没有任何请假申请流程</p>
            </div>
        </div>
    </div>

    <!-- 系统健康状态 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body text-center">
                <i class="fas fa-server text-4xl text-info mb-4"></i>
                <h3 class="card-title justify-center">流程引擎状态</h3>
                <div class="badge badge-success badge-lg mt-2">正常运行</div>
            </div>
        </div>
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body text-center">
                <i class="fas fa-database text-4xl text-success mb-4"></i>
                <h3 class="card-title justify-center">数据库连接</h3>
                <div class="badge badge-success badge-lg mt-2">连接正常</div>
            </div>
        </div>
        <div class="card bg-base-100 shadow-xl">
            <div class="card-body text-center">
                <i class="fas fa-cogs text-4xl text-warning mb-4"></i>
                <h3 class="card-title justify-center">系统性能</h3>
                <div class="badge badge-success badge-lg mt-2">运行良好</div>
            </div>
        </div>
    </div>
</div>

<!-- 流程详情模态框 -->
<dialog id="processDetailModal" class="modal">
    <div class="modal-box w-11/12 max-w-4xl">
        <h3 class="font-bold text-xl mb-6">
            <i class="fas fa-info-circle text-info mr-2"></i>
            流程详情
        </h3>

        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="card bg-base-200">
                <div class="card-body">
                    <h4 class="card-title">基本信息</h4>
                    <div class="space-y-2">
                        <div><strong>流程ID:</strong> <span id="detailProcessId">-</span></div>
                        <div><strong>申请人:</strong> <span id="detailApplicant">-</span></div>
                        <div><strong>请假天数:</strong> <span id="detailDays">-</span></div>
                        <div><strong>开始时间:</strong> <span id="detailStartTime">-</span></div>
                        <div><strong>当前状态:</strong> <span id="detailStatus">-</span></div>
                    </div>
                </div>
            </div>
            <div class="card bg-base-200">
                <div class="card-body">
                    <h4 class="card-title">请假信息</h4>
                    <div class="space-y-2">
                        <div><strong>请假原因:</strong> <span id="detailReason">-</span></div>
                        <div><strong>开始日期:</strong> <span id="detailStartDate">-</span></div>
                        <div><strong>结束日期:</strong> <span id="detailEndDate">-</span></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流程历史 -->
        <div class="card bg-base-200 mb-6">
            <div class="card-body">
                <h4 class="card-title mb-4">流程历史</h4>
                <div id="processHistory" class="space-y-2">
                    <!-- 历史记录将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>

        <div class="modal-action">
            <button class="btn" onclick="document.getElementById('processDetailModal').close()">关闭</button>
        </div>
    </div>
</dialog>

<script>
    let statusChart, trendChart;

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        initCharts();
        loadStatistics();
        loadProcesses();

        // 每30秒自动刷新数据
        setInterval(() => {
            loadStatistics();
            loadProcesses();
        }, 30000);
    });

    // 初始化图表
    function initCharts() {
        // 状态分布饼图
        const statusCtx = document.getElementById('statusChart').getContext('2d');
        statusChart = new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['运行中', '已完成', '已驳回'],
                datasets: [{
                    data: [0, 0, 0],
                    backgroundColor: ['#3B82F6', '#10B981', '#EF4444'],
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // 趋势折线图
        const trendCtx = document.getElementById('trendChart').getContext('2d');
        trendChart = new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '申请数量',
                    data: [],
                    borderColor: '#10B981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    // 加载统计数据
    // async function loadStatistics() {
    //     try {
    //         // 模拟统计数据
    //         const stats = {
    //             running: Math.floor(Math.random() * 10) + 1,
    //             completed: Math.floor(Math.random() * 50) + 20,
    //             avgTime: (Math.random() * 24 + 1).toFixed(1),
    //             approvalRate: Math.floor(Math.random() * 20 + 75)
    //         };
    //
    //         document.getElementById('runningProcesses').textContent = stats.running;
    //         document.getElementById('completedProcesses').textContent = stats.completed;
    //         document.getElementById('avgProcessTime').textContent = stats.avgTime;
    //         document.getElementById('approvalRate').textContent = stats.approvalRate + '%';
    //
    //         // 更新图表数据
    //         statusChart.data.datasets[0].data = [stats.running, stats.completed, Math.floor(stats.completed * 0.1)];
    //         statusChart.update();
    //
    //         // 更新趋势图（最近7天）
    //         const trendData = [];
    //         const trendLabels = [];
    //         for (let i = 6; i >= 0; i--) {
    //             const date = new Date();
    //             date.setDate(date.getDate() - i);
    //             trendLabels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
    //             trendData.push(Math.floor(Math.random() * 8) + 1);
    //         }
    //         trendChart.data.labels = trendLabels;
    //         trendChart.data.datasets[0].data = trendData;
    //         trendChart.update();
    //
    //     } catch (error) {
    //         console.error('加载统计数据失败:', error);
    //     }
    // }

    async function loadStatistics() {
        try {
            // 调用后端统计接口
            const response = await fetch('/api/statistics');
            if (!response.ok) {
                throw new Error('获取统计数据失败: ' + response.status);
            }
            const stats = await response.json();

            // 更新统计数字
            document.getElementById('runningProcesses').textContent = stats.running;
            document.getElementById('completedProcesses').textContent = stats.completed;
            document.getElementById('avgProcessTime').textContent = stats.avgTime;
            document.getElementById('approvalRate').textContent = stats.approvalRate + '%';

            // 更新图表数据
            statusChart.data.datasets[0].data = [stats.running, stats.completed, Math.floor(stats.completed * 0.1)];
            statusChart.update();

            // 更新趋势图（最近7天）
            // 转换日期格式（后端返回的是数字如804，表示8月4日）
            const trendLabels = stats.trendLabels.map(label => {
                const month = Math.floor(label / 100);
                const day = label % 100;
                return `${month}月${day}日`;
            });

            trendChart.data.labels = trendLabels;
            trendChart.data.datasets[0].data = stats.trendData;
            trendChart.update();

        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    // 加载流程实例
    // async function loadProcesses() {
    //     try {
    //         // 模拟流程数据
    //         const processes = generateMockProcesses();
    //         console.log(processes)
    //         const tableBody = document.getElementById('processTableBody');
    //         const emptyState = document.getElementById('emptyState');
    //
    //         if (processes.length === 0) {
    //             tableBody.innerHTML = '';
    //             emptyState.classList.remove('hidden');
    //         } else {
    //             emptyState.classList.add('hidden');
    //             tableBody.innerHTML = processes.map(process => createProcessRow(process)).join('');
    //         }
    //
    //     } catch (error) {
    //         console.error('加载流程数据失败:', error);
    //         document.getElementById('processTableBody').innerHTML =
    //             '<tr><td colspan="7" class="text-center text-error">加载失败，请刷新重试</td></tr>';
    //     }
    // }
    async function loadProcesses() {
        try {
            // 调用后端接口（替换模拟数据）
            const response = await fetch('/api/processes'); // 后端接口地址
            if (!response.ok) {
                throw new Error('接口请求失败: ' + response.status);
            }
            const processes = await response.json(); // 解析JSON数据
            console.log('从后端获取的流程数据:', processes);

            const tableBody = document.getElementById('processTableBody');
            const emptyState = document.getElementById('emptyState');

            if (processes.length === 0) {
                tableBody.innerHTML = '';
                emptyState.classList.remove('hidden');
            } else {
                emptyState.classList.add('hidden');
                // 调用createProcessRow渲染每一行（确保字段与后端返回的ProcessInstanceVO一致）
                tableBody.innerHTML = processes.map(process => createProcessRow(process)).join('');
            }

        } catch (error) {
            console.error('加载流程数据失败:', error);
            document.getElementById('processTableBody').innerHTML =
                '<tr><td colspan="7" class="text-center text-error">加载失败，请刷新重试</td></tr>';
        }
    }

    // 生成模拟流程数据
    // function generateMockProcesses() {
    //     const processes = [];
    //     const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
    //     const statuses = ['申请中', '领导审批中', '老板审批中', '已完成', '已驳回'];
    //
    //     for (let i = 0; i < Math.floor(Math.random() * 10) + 5; i++) {
    //         const startTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000);
    //         const status = statuses[Math.floor(Math.random() * statuses.length)];
    //         const days = Math.floor(Math.random() * 10) + 1;
    //
    //         processes.push({
    //             id: 'PROC-' + Math.random().toString(36).substr(2, 8).toUpperCase(),
    //             applicant: names[Math.floor(Math.random() * names.length)],
    //             days: days,
    //             status: status,
    //             startTime: startTime,
    //             duration: Math.floor((Date.now() - startTime.getTime()) / (1000 * 60 * 60))
    //         });
    //     }
    //
    //     return processes.sort((a, b) => b.startTime - a.startTime);
    // }

    // 创建流程行
    function createProcessRow(process) {
        const statusBadge = getStatusBadge(process.status);
        const durationText = `${process.duration}天`;

        return `
                <tr class="hover">
                    <td class="font-mono text-sm">${process.id}</td>
                    <td>
                        <div class="flex items-center space-x-2">
                            <i class="fas fa-user text-primary"></i>
                            <span>${process.applicant}</span>
                        </div>
                    </td>
                    <td>
                        <div class="badge badge-outline">${process.duration} 天</div>
                    </td>
                    <td>${statusBadge}</td>
                    <td class="text-sm">${process.startTime.toLocaleString('zh-CN')}</td>
                    <td class="text-sm">${durationText}</td>
                    <td>
                        <button class="btn btn-ghost btn-sm" onclick="showProcessDetail('${process.id}')">
                            <i class="fas fa-eye mr-1"></i>
                            详情
                        </button>
                    </td>
                </tr>
            `;
    }

    // 获取状态徽章
    function getStatusBadge(status) {
        const badges = {
            '申请中': '<div class="badge badge-info">申请中</div>',
            '领导审批中': '<div class="badge badge-warning">领导审批中</div>',
            '老板审批中': '<div class="badge badge-warning">老板审批中</div>',
            '已完成': '<div class="badge badge-success">已完成</div>',
            '已驳回': '<div class="badge badge-error">已驳回</div>'
        };
        return badges[status] || '<div class="badge badge-ghost">未知</div>';
    }

    // 显示流程详情
    // function showProcessDetail(processId) {
    //     // 模拟流程详情数据
    //     document.getElementById('detailProcessId').textContent = processId;
    //     document.getElementById('detailApplicant').textContent = '张三';
    //     document.getElementById('detailDays').textContent = '3天';
    //     document.getElementById('detailStartTime').textContent = new Date().toLocaleString('zh-CN');
    //     document.getElementById('detailStatus').textContent = '领导审批中';
    //     document.getElementById('detailReason').textContent = '家中有事需要处理';
    //     document.getElementById('detailStartDate').textContent = '2024-01-15';
    //     document.getElementById('detailEndDate').textContent = '2024-01-17';
    //
    //     // 模拟流程历史
    //     const history = [
    //         { step: '流程开始', time: '2024-01-14 09:00:00', status: '完成' },
    //         { step: '员工申请', time: '2024-01-14 09:05:00', status: '完成' },
    //         { step: '领导审批', time: '2024-01-14 14:30:00', status: '进行中' }
    //     ];
    //
    //     const historyHtml = history.map(h => `
    //             <div class="flex justify-between items-center p-2 bg-base-100 rounded">
    //                 <span>${h.step}</span>
    //                 <span class="text-sm text-base-content/70">${h.time}</span>
    //                 <div class="badge ${h.status === '完成' ? 'badge-success' : 'badge-warning'}">${h.status}</div>
    //             </div>
    //         `).join('');
    //
    //     document.getElementById('processHistory').innerHTML = historyHtml;
    //     document.getElementById('processDetailModal').showModal();
    // }
    async function showProcessDetail(processId) {
        try {
            // 调用后端接口获取流程详情
            const response = await axios.get(`/api/processes/${processId}/detail`);
            if (!response.data.success) {
                alert(response.data.message);
                return;
            }

            const detail = response.data;

            // 更新流程基本信息
            document.getElementById('detailProcessId').textContent = detail.processId;
            document.getElementById('detailApplicant').textContent = detail.applicant || '未知';
            document.getElementById('detailDays').textContent = detail.days ? detail.days + '天' : '未知';
            document.getElementById('detailStartTime').textContent = detail.startTime || '';
            document.getElementById('detailStatus').textContent = detail.status || '未知';
            document.getElementById('detailReason').textContent = detail.reason || '无';
            document.getElementById('detailStartDate').textContent = detail.startDate || '';
            document.getElementById('detailEndDate').textContent = detail.endDate || '';

            // 生成流程历史HTML
            const historyHtml = detail.history.map(h => `
                <div class="flex justify-between items-center p-2 bg-base-100 rounded">
                    <span>${h.step}</span>
                    <span class="text-sm text-base-content/70">${h.time}</span>
                    <div class="badge ${h.status === '完成' ? 'badge-success' : 'badge-warning'}">${h.status}</div>
                </div>
            `).join('');

            document.getElementById('processHistory').innerHTML = historyHtml;
            document.getElementById('processDetailModal').showModal();

        } catch (error) {
            console.error('加载流程详情失败:', error);
            alert('加载流程详情失败，请重试');
        }
    }

    // 过滤流程
    function filterProcesses() {
        loadProcesses(); // 简化实现，直接重新加载
    }
</script>
</body>
</html>